use std::process::{Command, Stdio};
use std::io::{self, BufRead};
use clap::command;
use crate::Mutiple;

pub fn run(command:String,args:&[&str]) {
    let mut child = Command::new(command)
        .args(args)
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to execute process");

    let stdout = child.stdout.take().unwrap();
    let reader = io::BufReader::new(stdout);

    for line in reader.lines() {
        println!("{}", line.unwrap());
    }

    let status = child.wait().expect("failed to wait for child");
    println!("exited with: {}", status);
}

pub fn subcommand_run(command:String,img:String){
    if  !img.eq( "instantbox/ubuntu:18.04") {
        println!("run customer img");
        let run_array = ["run", "-d",img.as_str()];
        run(command,&run_array);
    }else {
        println!("run default img");
        let run_array = ["run", "-d", "-p", "1589:1589", "instantbox/ubuntu:18.04", "ttyd_linux.x86_64", "-p", "1589", "bash"];
        run(command,&run_array);
    }

}
pub fn subcommand_exec(command:String,mutiple:Mutiple){
    let mut vec = mutiple.exec.clone();
    if vec.len()<2{println!("exec [OPTIONS] COMMAND");return;}

    let mut exec_array:Vec<&str> = vec![];

    for command in vec.iter() {

        exec_array.push(command.as_str());
    }
   let length = exec_array.len();
//    exec_array.swap(0, length -1);
//    println!("{:?}", exec_array);

    run(command,&exec_array[0..length])

}